package eva

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"
	"trusteva/app/eva/model"
)

type ExportWarningLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewExportWarningLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExportWarningLogic {
	return &ExportWarningLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ExportWarningLogic) ExportWarning(req *types.ExportWarningRo) (resp *types.ExportWarningRsp, err error) {
	sess := l.svcCtx.DB.WithContext(l.ctx).Model(&model.Warning{})
	if req.AppName != "" {
		sess = sess.Where("AppName like ?", "%"+req.AppId+"%")
	}
	if req.AppId != "" {
		sess = sess.Where("AppId=?", req.AppId)
	}
	if req.DeviceId != "" {
		sess = sess.Where("DeviceId=?", req.DeviceId)
	}

	var beans []model.Warning
	if err := sess.Order("ID DESC").Find(&beans).Error; err != nil {
		return nil, err
	}
	resp = new(types.ExportWarningRsp)
	for _, v := range beans {
		resp.Data = append(resp.Data, types.ListWarningData{
			Id:        v.ID,
			CreatedAt: v.CreatedAt.Format(time.RFC3339),
			AppName:   v.AppId,
			AppId:     v.AppId,
			DeviceId:  v.DeviceId,
			Memo:      v.Memo,
			DstIP:     v.DstIP,
			DstPort:   v.DstPort,
			Desc:      v.Desc,
			Level:     v.Level,
		})
	}

	return
}
